package com.hermes.comics.dialogs;

import android.app.ProgressDialog;
import android.app.Activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.net.Uri;

import android.widget.Toast;

import com.hermes.comics.MainActivity;
import com.hermes.comics.R;
import com.hermes.comics.data.Constants;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import java.net.HttpURLConnection;

import java.nio.charset.Charset;

import java.util.List;

/**
 */
public class RefreshCatalogDialog extends RemoteCatalogDialog implements RemoteCatalogDialog.Interface {
   
  private static final String GDRIVE_KEY = "0AkFOipE2LA6KdDhMYU1yQVU3SHduUHhVVkh1Y1p6Qmc";
  private static final String PREFIX_DOWNLOAD_DATA_URI = 
      "https://docs.google.com/spreadsheet/pub?key=" + GDRIVE_KEY + "&output=txt";

  private static final String SERIES_URI = PREFIX_DOWNLOAD_DATA_URI + "&gid=0";
  private static final String ISSUES_URI = PREFIX_DOWNLOAD_DATA_URI + "&gid=1";

  private String seriesContent = null;

  public RefreshCatalogDialog(Activity activity) {
    super(activity);

    setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    setMax(2);
    setProgress(0);
    setIndeterminate(false);
    setProgressNumberFormat("");
    setMessage(getContext().getString(R.string.please_wait));
    setTitle(activity.getString(R.string.download_title));
  }

  private boolean isSeries() {
    return (seriesContent == null);
  }

  @Override
  public String getUrl() {
    return isSeries() ? SERIES_URI : ISSUES_URI;
  }

  @Override
  public void onFailure(UrlWrapper result) {
    Toast.makeText(getContext(), "Error http status = " + result.httpStatus(), Toast.LENGTH_LONG).show();
    abort();
  }

  @Override
  public void onPreExecute() {
    setProgressNumberFormat(isSeries() ? "Fetching series..." : "Fetching issues...");
  }

  @Override
  public void onCancelled() {
    dismiss();
  }

  @Override
  public void onSuccess(UrlWrapper url) {
    if (isSeries()) {
      seriesContent = url.content();
      execute(this);
      setProgress(1);
    } else {
      save(Constants.SERIES_FILENAME, seriesContent);
      save(Constants.ISSUES_FILENAME, url.content());
      dismiss();
      getActivity().finish();
      getContext().startActivity(new Intent(getContext(), MainActivity.class));
    }
  }

  private void save(String filename, String content) {
    try {
      File file = new File(Constants.DB_PATH, filename);
      OutputStreamWriter out = new OutputStreamWriter(
          new FileOutputStream(file), Charset.forName("UTF-8"));
      out.write(content);
      out.flush();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  public void show() {
    super.show();
    execute(this);
  }
}
